package cn.seaboot.admin.images.service;

import cn.seaboot.admin.images.bean.SysIcon;
import cn.seaboot.admin.images.bean.SysImage;
import cn.seaboot.admin.images.consts.IconType;
import cn.seaboot.admin.images.dao.SysIconDao;
import cn.seaboot.admin.upload.OutputInfo;
import cn.seaboot.commons.core.*;
import cn.seaboot.commons.digest.Base64;
import cn.seaboot.commons.file.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Service
 * 图标 [t_image_icon]
 *
 * @author Mr.css on 2018-6-20
 */
@Service
public class SysIconService {
    private Logger logger = LoggerFactory.getLogger(SysIconService.class);
    private final Snowflake snowflake = SnowflakeFactory.createSnowflake();

    @Resource
    private SysIconDao sysIconDao;

    /**
     * 增
     *
     * @return affected rows
     */
    public SysIcon create(String txt, String color, Integer fontSize, Integer width, Integer height) throws IOException {
        // color
        int rgb = Integer.parseInt(color.substring(1), 16);
        Color backgroundColor = new Color(rgb);

        // font
        Font font = new Font("黑体", Font.PLAIN, fontSize);

        // text
        String content = txt.length() > 2 ? txt.substring(0, 2) : txt;

        // gen
        BufferedImage image = BufferedImageUtil.createFontIcon(content, backgroundColor, font, width, height);
        String base64 = Base64ImageUtils.imageToBase64(image, "png");

        SysIcon pojo = new SysIcon();
        pojo.setId(snowflake.nextId());

        pojo.setIconType(IconType.USER);
        pojo.setContent(base64);
        pojo.setIconName(txt + ".png");
        pojo.setDescription(txt);

        sysIconDao.insert(pojo);
        return pojo;
    }

    /**
     * 增
     *
     * @param pojo pojo
     * @return affected rows
     */
    public int insert(SysIcon pojo) {
        return sysIconDao.insert(pojo);
    }


    /**
     * 保存图片
     *
     * @param file 文件实体
     * @param type 图片类型，主要用于区分业务，方便资源管理
     * @return SysImage
     * @throws IOException 磁盘操作异常
     */
    public SysIcon upload(Integer type, @NotNull MultipartFile file) throws IOException {
        String original = file.getOriginalFilename();
        Asserts.notNull(original, "filename is null");

        // 保留扩展名，保留后 32 位
        String filename = StringUtils.truncateHead(original, 32);

        String base64 = Base64ImageUtils.imageToBase64(file.getInputStream());

        SysIcon icon = new SysIcon();
        icon.setId(snowflake.nextId());

        icon.setIconType(type);
        icon.setContent(base64);
        icon.setIconName(filename);
        icon.setDescription(original);

        sysIconDao.insert(icon);
        return icon;
    }

    /**
     * 删
     *
     * @param id id
     * @return affected rows
     */
    public int deleteById(Long id) {
        return sysIconDao.deleteById(id);
    }

    /**
     * 改
     *
     * @param pojo pojo
     * @return affected rows
     */
    public int updateById(SysIcon pojo) {
        return sysIconDao.updateSampleById(pojo);
    }

    /**
     * 查
     *
     * @param id id
     * @return pojo
     */
    public SysIcon queryById(Long id) {
        return sysIconDao.selectById(id);
    }

    /**
     * 查列表
     *
     * @param params 参数
     * @return list
     */
    public List<SysIcon> queryList(Map<String, Object> params) {
        return sysIconDao.selectList(params);
    }


    /**
     * 打包下载全部图标
     *
     * 将 base64 转为图片下载
     *
     * @param params   过滤参数
     * @param response -
     * @throws IOException -
     */
    public void download(Map<String, Object> params, HttpServletResponse response) throws IOException {
        List<SysIcon> list = sysIconDao.selectList(params);
        if (CommonUtils.isNotEmpty(list)) {
            response.setContentType(MediaType.APPLICATION_ZIP_VALUE);
            ResponseWriter.setAttachName(response, "icons.zip");

            try (ZipWriter writer = new ZipWriter(response.getOutputStream())) {
                for (SysIcon icon : list) {
                    try {
                        writer.write(Base64.decodeString(icon.getContent()), icon.getIconName());
                    } catch (Exception e) {
                        // ignore write failed!
                        logger.debug("write file failed: {}", icon.getIconName(), e);
                    }
                }
                writer.finish();
            }
        }
    }
}
